package com.vlong.town.util.interceptor;

import com.vlong.town.util.common.TownConstant;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * PromiseInteceptor
 *
 * @author Assassin
 */
@Component
public class PromiseInterceptor extends HandlerInterceptorAdapter {

    // Fields

    private static Logger logger = LogManager.getLogger(PromiseInterceptor.class);

    /**
     * 请求拦截处理
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 判断请求类型（Ajax 或者 普通请求）
        boolean isAjaxRequest = false;
        if (!((request.getHeader("accept") != null && request.getHeader("accept").contains("application/json")) || (request.getHeader("X-Requested-With") != null
                && request.getHeader("X-Requested-With").contains("XMLHttpRequest")))) {
            isAjaxRequest = false;
        } else {
            isAjaxRequest = true;
        }


        // 获取请求路径以及参数信息
        String uri = request.getRequestURI();
        String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI() + "?" + request.getQueryString();
        String params = request.getQueryString();

        logger.info("RequestURI => " + uri);
        logger.info((isAjaxRequest ? "Ajax->当前请求路径" : "当前请求路径") + "=>" + url);
        logger.info((isAjaxRequest ? "Ajax->当前请求参数" : "当前请求参数") + "=>" + params);

        // 判断是否是系统的URI
        boolean isSysUri = false;
        for(String sysUri : TownConstant.SYSTEM_URIS) {
            if(("/town" + sysUri).contains(uri)) {
                isSysUri = true;
                break;
            }
        }

        // 定义不需要拦截的请求路径
        String[] withoutInteceptor = new String[]{ "/js", "/css", "/images", "/fonts", "/admin/login", "/executeLogin","/logout", "/client/logout", "/client/", "/cdkeditor/", "/error"};

        // 获取源地址
        String sourceUrl = request.getHeader("REFERER");
        boolean isInteceptor = true;
        for (String str : withoutInteceptor) {
            if (uri.indexOf(str) != -1) {
                isInteceptor = false;
                break;
            }
        }

        // 不是系统的URI页面不拦截
        if(!isSysUri) {
            isInteceptor = false;
        }

        // 项目根目录
        if(uri.equals("/town/")) {
            isInteceptor = false;
        }

        if (isInteceptor) {
            if ((sourceUrl == null || "".equals(sourceUrl.trim()))) {
                gotoLoginPage(request, response);
                return false;
            }
            // 记录原地址
            request.getSession().setAttribute("sourceUrl", uri);
            String userType= (String)request.getSession().getAttribute(TownConstant.TOWN_SESSION_USER_TYPE);
            Object sessionUser = request.getSession().getAttribute(TownConstant.TOWN_SESSION_USER);
            if (sessionUser == null||userType.equals(TownConstant.TOWN_SESSION_USER_TYPE_CLIENT)) {
                gotoLoginPage(request, response);
            }
        }
        return super.preHandle(request, response, handler);
    }

    /**
     * 跳转到登录页面
     *
     * @param request  HttpServletRequest request
     * @param response HttpServletResponse response
     * @throws IOException
     */
    public void gotoLoginPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter out = response.getWriter();
        StringBuilder builder = new StringBuilder();
        String default_url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
        builder.append("<script>");
        builder.append("window.parent.location.href='" + default_url + "/admin/login'");
        builder.append("</script>");
        out.print(builder.toString());
        out.close();
    }

}